package com.guodi.model.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.AjaxResult;
import com.guodi.model.service.INatResourcesService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.*;

@Service
public class NatResourcesServiceImpl implements INatResourcesService {

    private static Map<String, String> titleColumn = new HashMap<>();
    {
        titleColumn.put("行政区划编码", "divisionCode");
        titleColumn.put("行政区划名称", "divisionName");
        titleColumn.put("指标名称", "name");
        titleColumn.put("指标时间", "year");
        titleColumn.put("单位", "unit");
        titleColumn.put("指标值", "value");
        titleColumn.put("X坐标", "x");
        titleColumn.put("y坐标", "y");
    }
    @Override
    public AjaxResult analysisToMap(MultipartFile file) throws IOException {
        Set<Object> nameSet = new HashSet<>();
        Set<Object> yearSet = new HashSet<>();
        InputStream inputStream = file.getInputStream();
        Workbook wb = WorkbookFactory.create(inputStream);
        inputStream.close();
        Sheet sheet = wb.getSheetAt(0);
        int rowEnd = sheet.getLastRowNum(); //最后一行数据
        int rowStart = 1; //从第二行开始
        //封装excel数据到list中
        Map<String, JSONArray> map = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        Row titleRow = sheet.getRow(0);
        //获取内容信息
        for (int i = rowStart; i <= rowEnd; ++i) {
            Row currentRow = sheet.getRow(i);
            if (Objects.isNull(currentRow)) {
                continue;
            }
            String firstValue = getCellValueString(currentRow.getCell(0));
            if((firstValue != null && firstValue.indexOf("注") == 0) || StringUtils.isBlank(firstValue)) {
                break;
            }
            String name = null;
            String year = null;
            if(nameSet.size() > 1 && yearSet.size() > 1) {
                return new AjaxResult(StatusCode.REQUEST_CODE_OPERATION_FAILURE, "上传数据有重复，不符合要求");
            }
            JSONObject object = new JSONObject();
            for (int j = 0; j < currentRow.getLastCellNum(); ++j) {
                Cell cell = currentRow.getCell(j);
                String title = getCellValueString(titleRow.getCell(j));
                if(cell != null) {
                    String key = titleColumn.get(title);
                    Object value;
                    if("name".equals(key)) {
                        name = getCellValueString(cell);
                        nameSet.add(name);
                    }
                    if("year".equals(key)) {
                        value = getCellValue(cell);
                        if(value instanceof Double) {
                            value = String.valueOf(((Double) value).intValue());
                        }
                        yearSet.add(value);
                        year = String.valueOf(value);
                    } else {
                        value = getCellValue(cell);
                        if(value instanceof Double) {
                            NumberFormat nf = NumberFormat.getInstance();
                            nf.setMaximumFractionDigits(10);
                            nf.setGroupingUsed(false);
                            value = nf.format(value);
                        }
                    }
                    object.put(key, value);
                }
            }
            JSONArray group = map.get(name + "-" + year);
            if(group == null) {
                group = new JSONArray();
                map.put(name + "-" + year, group);
            }
            group.add(object);
        }
        return new AjaxResult(map);
    }
    public String getCellValueString(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        //判断数据的类型
        switch (cell.getCellType()) {
            case NUMERIC: //数字
                // 判断是否是时间戳
//                if (HSSFDateUtil.isCellDateFormatted(cell)) {
//                    Date date = cell.getDateCellValue();
//                    if(columns.length > 0) {
//                        SimpleDateFormat sdf1 = new SimpleDateFormat(columns[0].format());
//                        cellValue = sdf1.format(date);
//                    } else {
//                        cellValue = date.toString();
//                    }
//                } else {
//                    cellValue = String.valueOf(cell.getNumericCellValue());
//                }
                Double value = cell.getNumericCellValue();
                cellValue = String.valueOf(value.intValue());
                break;
            case STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            default:
                cellValue = "";
        }
        return cellValue;
    }
    public Object getCellValue(Cell cell) {
        Object cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        //判断数据的类型
        switch (cell.getCellType()) {
            case NUMERIC: //数字
                cellValue = cell.getNumericCellValue();
                break;
            case STRING: //字符串
                cellValue = cell.getStringCellValue();
                break;
            default:
                cellValue = "";
        }
        return cellValue;
    }
}
